<?php
namespace plugins\appmarket\controller; //Demo插件英文名，改成你的插件英文就行了
use cmf\controller\PluginAdminBaseController;//引入此类
use think\Db;
use think\Validate;
use think\Cache;
use think\Config;
use app\common\lib\AccessAuthorization;
use plugins\appmarket\controller\ModuleCategoryController;
use plugins\appmarket\lib\Upload;
use plugins\appmarket\controller\ConfigController;
use plugins\appmarket\controller\PublishController;

/**
 * 前端模板上传页面
 */
class TemplateController extends PluginAdminBaseController
{
    /**
     * 文件存储根目录
     * @var string
     */
    private $rootPath = "upload/module";

   	protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id();
        //获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
    }

    static public $statusColor = [ '#FF9800' , '#007AAE' , 'red' , 'green' ];
    //模板状态
    // 0 1 2 3
    static public $statusStr = ['未提交','审核中','审核失败','已通过']; 

    /**
     * 前端模板首页
     * @adminMenu(
     *     'name'   => '模板管理首页',
     *     'parent' => 'AdminIndex/index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '模板管理首页',
     *     'param'  => ''
     * )
     */
    public function index ()
    {
        $data = $this->request->param();
        $search = [
            'search'    =>  isset( $data [ 'search' ] ) ? $data [ 'search' ] : NULL,
            'module'    =>  isset( $data [ 'module' ] ) ? $data [ 'module' ] : 100,
            'author'    =>  isset( $data [ 'author' ] ) ? $data [ 'author' ] : 100,
            'putway'    =>  isset( $data [ 'putway' ] ) ? $data [ 'putway' ] : 100,
            'charge'    =>  isset( $data [ 'charge' ] ) ? $data [ 'charge' ] : 100,
            'status'    =>  isset( $data [ 'status' ] ) ? $data [ 'status' ] : 100,
			'type'    =>  isset( $data [ 'type' ] ) ? $data [ 'type' ] : 100,
        ];

        $list = Db::name( 'module_template' );//->order('status')->select()->toArray();
        $accessIds = AccessAuthorization::getAccessibleIdsByUserId( cmf_get_current_admin_id() );
        if( !Cache::has('appmarket_user_list') || empty( $appmarketUserList=Cache::get('appmarket_user_list') ) ){
            
            $appmarketUserList = Db::name( 'user' )->where( 'id' , 'IN' , $accessIds )->field( 'id,user_login' )->select()->toArray();
            Cache::set( 'appmarket_user_list' , $appmarketUserList  );
        }
        $list = $list -> where( 'author_id' , 'IN' , $accessIds );
        //搜索参数
        if( !empty( $search [ 'search' ] ) ){
            //模块标识
            if( $search [ 'module' ] != 100 ){
                $list = $list->where( 'name' , 'LIKE' , $search [ 'module' ]  );
            }
            //作者
            if( $search [ 'author' ] != 0 ){
                $list = $list->where( 'author_id' , '=' , $search [ 'author' ]  ) ;
            }
            //状态
            if( $search [ 'status' ] != 100 ){
                $list = $list->where( 'status' , '=' , $search [ 'status' ] );
            }
            //付费
            if( $search [ 'charge' ] != 100 ){
                if( $search [ 'charge' ] == 0 ){
                    //免费
                    $list = $list->where( 'price' , '=' , 0 );
                }else if( $search [ 'charge' ]  == 1 ){
                    //收费
                    $list = $list->where( 'price' , '>' , 0 );
                }
               
            }
            //上架
            if( $search [ 'putway' ] != 100 ){
                $list = $list->where( 'putway' , '=' , $search [ 'putway' ] );
            }
			
			//运行端
			if( $search [ 'type' ] != 100 ){
				$list = $list ->where( 'type' , 'like' , $search['type']);
			}

        }
        
        $list = $list ->order( 'status ASC' )->paginate( 20 );
        
        //获取模块列表
        $moduleList = $this->getModuleList();
		
		//获取类型列表
		$typeList = Db::name('module_template_classify')->select()->toArray();
		
		$this->assign( 'typeList' , $typeList );

        $this->assign( 'statusColor' , self::$statusColor );
        $this->assign( 'statusStr' , self::$statusStr );
        $this->assign( 'userList' , $appmarketUserList );
        $this->assign( 'search' , $search );
        $this->assign( 'moduleList' , $moduleList );
        $this->assign( 'list' , $list );
        return $this->fetch( 'template/index' );
    }

    /**
     * 发布模块页面
     * @adminMenu(
     *     'name'   => '发布模板',
     *     'parent' => 'index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '发布模板',
     *     'param'  => ''
     * )
     */
    public function publish()
    {
        $data = $this->request->param();
        $previewList = [];
        if( isset( $data['id'] ) && !empty( $data ['id'] ) ){
            //读取已有模块
            $module = Db::name( 'module_template' )->where( 'id' , $data ['id'] )->find();
            if( in_array($module [ 'status' ] , [1,2] ) ){
                //跳转到审核结果页面
                return $this->auditResult( $data['id'] );
            }else{
                if( !empty($module['preview']) ){
                    $previewList = explode(',', $module['preview']);
                }
                $this->assign( 'module' , $module );
            }
            
        }

        $moduleList = $this->getModuleList();
		
		$typeList = $this->getTempType();
		
		$this->assign( 'typeList' , $typeList );
		
        $this->assign( 'moduleList' , $moduleList );
        $this->assign( 'previewList' , $previewList );
        return $this->fetch('template/publish');
    }
	
	//获取模板类型
	private function getTempType ()
	{
		$typeList = Db::name('module_template_classify')->select()->toArray();
		return $typeList;
	}
	
	//getExistsTemplate 获取现有模板
	public function getExistsTemplate()
	{
		$param = $this->request->param();
		$list = Db::name( 'module_template' )->where( [ 'name'=>$param['name'] ] )->field('template_name,version')->order('version')->select()->toArray();
		return zy_json_echo(true , '' , $list);
	}
	
	
	
	
    /**
     * 发布模板数据保存
     * @return [type] [description]
     * @adminMenu(
     *     'name'   => '发布模板保存提交',
     *     'parent' => 'publish',
	 
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '发布模板保存提交',
     *     'param'  => ''
     * )
     */
    public function templateSave()
    {
        $param = $this->request->param();
        $data = [];
        $res = Db::name( 'module_template' )->insertGetId( $data );
        if( !$res ){
            return zy_json_echo( false , '数据保存失败,请稍后再试!' );
        }
        return zy_json_echo( true , '数据保存成功!' );
    }

    /**
     * 模板发布提交
     * @adminMenu(
     *     'name'   => '模板发布提交审核',
     *     'parent' => 'publish',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '模板发布提交审核',
     *     'param'  => ''
     * )
     */
    public function publishPost()
    {
        $param = $this->request->param();
        $type = $param[ 'type' ];
        $data = $param [ 'data' ]; 
        if( $type == 'save' ){
			
			if( isset( $param [ 'id'] ) && !empty( $param [ 'id' ] )  ){
				//更新数据
				$res = Db::name( 'module_template' )->where( 'id' , $param [ 'id' ] )->update( $data );
				if( !$res ){
					return zy_json_echo( false , '保存数据失败,请稍后再试!' );
				}
				return  zy_json_echo( true , '保存数据成功',cmf_plugin_url( 'Appmarket://Template/publish')."?id=".$param[ 'id' ]  );
			}else{
				//保存数据
			
				$data['author_id'] = cmf_get_current_admin_id();
				$data [ 'author' ] = Db::name( 'user' )->where( 'id' , $data [ 'author_id' ] )->value('user_login');
				$data [ 'add_time' ] = time();
				$data [ 'module_store_id' ] = Db::name( 'module_store' )->where( [ 'name'=>$data['name'] , 'version'=>$data['version'] ] )->value('id'); 
				//保存
				$templateId = Db::name('module_template')->insertGetId($data);
				if( !$templateId ){
					return zy_json_echo( false , '保存数据失败,请稍后再试!' );
				}
				return zy_json_echo( true , '保存数据成功!' , cmf_plugin_url( 'Appmarket://Template/publish')."?id=$templateId" );
			}
        }else{
            $id = $param ['id'];
            $data ['status'] = 1;//审核中
            $res = Db::name( 'module_template' )->where( 'id' , $id )->update( $data );
            if( !$res ){
                return zy_json_echo( false , '提交审核失败,请稍后再试!' );
            }
            $log['template_id'] = $id;
            $log['content'] = '<span style="color:blue;" class="glyphicon glyphicon-refresh"></span>提交审核成功，请等待！';
            //写入拒绝日志
            PublishController::addLog($log);
            //提交审核成功 ,跳转到审核结果页面
            return zy_json_echo( true, '提交审核成功!' , cmf_plugin_url( 'Appmarket://Template/auditResult' )."?templateId=$id" );
        }
    }
    /**
     * 模板删除
     * @adminMenu(
     *     'name'   => '模板删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '模板删除',
     *     'param'  => ''
     * )
     */
    public function del()
    {
        if( !$this->request->isPost() ){
            return zy_json_echo( false , '请求类型错误，请检查！' );
        }
        $data = $this->request->param();
        $id = $data['id'];
        $res = Db::name( 'module_template' )->where( 'id' , $id )->delete();
        if( !$res ){
            //删除日志信息
            Db::name( 'module_audit_log' )->where( 'template_id' , $id )->delete();
            return zy_json_echo( false , '删除失败，请稍后再试！' );
        }
        return zy_json_echo( true, '删除成功！' );
    }

    /**
     * 模板审核列表
     * @adminMenu(
     *     'name'   => '模板审核',
     *     'parent' => 'index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '模板审核',
     *     'param'  => ''
     * )
     */
    public function audit()
    {
        $list = Db::name( 'module_template' )->where( 'status' , 1 )->select()->toArray();
        $this->assign( 'list' , $list );
        return $this->fetch('template/audit');
    }

    /**
     * 模板审核结果显示页面
     * @adminMenu(
     *     'name'   => '审核结果',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '审核结果',
     *     'param'  => ''
     * )
     */
    public function auditResult( $templateId )
    {
        $module = Db::name('module_template')->where( 'id' , $templateId )->find();
        $where = [
            'template_id' => $templateId
        ];
        $logList = Db::name( 'module_audit_log' )->where( $where )->order('add_time desc')->select()->toArray();
        $logList = autoHtmlspecialcharsDecode($logList);
        $this->assign( 'template_name' , $module['template_name'] );
        $this->assign( 'status', $module['status'] );
        $this->assign( 'id' , $module[ 'id' ] );
        //$this->assign( 'module' , $module );
        $this->assign( 'logList' , $logList );
        return $this->fetch( 'template/audit_result' );
    }

    /**
     *重新提交数据
     *@adminMenu(
     *     'name'   => '重新提交数据',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '重新提交数据',
     *     'param'  => ''
     * )
     */
    public function reSubmit()
    {
        $data  = $this->request->param();
        $id = $data ['id'];
        $status = $data ['status'];
        $res = Db::name( 'module_template' )->where( 'id' , $id )->update( [ 'status' => $status ] );
        if( !$res ){
            return zy_json_echo(false,'操作错误！');
        }
        $url = cmf_plugin_url( 'Appmarket://Template/publish' ).'?id='.$id;
        return zy_json_echo (true , '页面跳转中，请稍等！', $url);            
    }

    /**
     * 上架/下架
     * @adminMenu(
     *     'name'   => '上架/下架',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '上架/下架',
     *     'param'  => ''
     * )
     */
    public function putway( $id , $num )
    {   
        try {
            $res = Db::name('module_template')->where( 'id' , $id )->update( [ 'putway' => $num ] );
            if( !$res ){
                return zy_json_echo( false, '操作失败，请稍后再试！' );
            }
            return zy_json_echo( true, '操作成功！');
        } catch (\Exception $e) {
            return zy_json_echo(false,'异常：'.$e->getMessage());
        }
    }

    /**
     * 详情
     * @adminMenu(
     *     'name'   => '模板详情',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '模板详情',
     *     'param'  => ''
     * )
     */
    public function particular( $id )
    {
        $module  = Db::name( 'module_template' )->where( 'id' , $id )->find();
        $previewList = [];
        if( !empty($module['preview']) ){
            $previewList = explode(',', $module['preview']);
        }
        $this->assign( 'module' , $module );
        $moduleList = $this->getModuleList();
        $this->assign( 'moduleList' , $moduleList );
        $this->assign( 'previewList' , $previewList );

        return $this->fetch( 'template/particular' );
    }

    /**
     * 审核通过
     * @adminMenu(
     *     'name'   => '审核通过',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '审核通过',
     *     'param'  => ''
     * )
     */
    public function pass( $id )
    {
        $status = 3;//通过审核更改状态为3
        $res = Db::name( 'module_template' )->where( 'id' , $id )->update( [ 'status' => $status ] );
        if( !$res ){
            return zy_json_echo(false , '操作失败,请稍后再试!' );
        }

        $log['template_id'] = $id;
        $log['content'] = '<span style="color:green;" class="glyphicon glyphicon-ok"></span> 审核通过!';
        //写入拒绝日志
        PublishController::addLog($log);
        return zy_json_echo( true , '操作成功' );
    }
    /**
     * 拒绝
     * @adminMenu(
     *     'name'   => '审核拒绝',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '审核拒绝',
     *     'param'  => ''
     * )
     */
    public function refuse()
    {   
        return $this->fetch( 'template/refuse' );
    }
    /**
     * 拒绝提交
     * @adminMenu(
     *     'name'   => '拒绝提交',
     *     'parent' => 'refuse',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 1000,
     *     'icon'   => '',
     *     'remark' => '拒绝提交',
     *     'param'  => ''
     * )
     */
    public function refusePost(  )
    {
        $param = $this->request->param();
        $id  = $param ['id'];
        $content = $param [ 'content' ]; 
        $status = 2;//被驳回
        $res = Db::name( 'module_template' )->where( 'id', $id )->update( [ 'status'=>$status ] );

        if( !$res ){
            return zy_json_echo(false , '操作失败,请稍后再试!' );
        }
        $log['template_id'] = $id;
        $log['content'] = '<div><span style="color:red;" class="glyphicon glyphicon-remove"></span>审核失败，拒绝理由：</div>'.$content;
        //写入拒绝日志
        PublishController::addLog($log);
        return zy_json_echo( true , '操作成功' );
    }

    /**
     * 上传思维导图文件
     */
    public function mindMap( $id )
    {
        $module = $this->getModuleInfo( $id );
        $path = cmf_parse_name( $module[ 'name' ] ).DS.$module['version'].DS.'template'.DS.$module['type'].DS.'mindMap';
        return $this->uploadFile ( $path , 10 , ['xmind','zip','rar'] );   
    }

    /**
     * 上传流程图文件
     */
    public function flowChart( $id )
    {
        $module = $this->getModuleInfo( $id );
        $path = cmf_parse_name( $module[ 'name' ] ).DS.$module['version'].DS.'template'.DS.$module['type'].DS.'flowChart';
        return $this->uploadFile ( $path , 10 , ['rp','zip','rar'] );
    }

    /**
     * 上传ui图文件
     */
    public function uiMap( $id )
    {
        $module = $this->getModuleInfo( $id );
        $path = cmf_parse_name( $module[ 'name' ] ).DS.$module['version'].DS.'template'.DS.$module['type'].DS.'uiMap';
        return $this->uploadFile ( $path , 10 , ['rp','zip','rar'] );
    }

    /**
     * 上传预览图
     */
    public function preview( $id )
    {
        $module = $this->getModuleInfo( $id );
        $path = cmf_parse_name( $module[ 'name' ] ).DS.$module['version'].DS.'template'.DS.$module['type'].DS.'preview';

        $timeMd5=md5(time());
        //产生随机数避免名字重复
        $start = rand(5,20);
        $length = rand(5,10);
        $fileName = substr( $timeMd5 , $start , $length );

        return $this->uploadFile ( $path , 10 , ['jpg','bmp','png','gif','jpeg'] , $fileName );
    }

    /**
     * 获取模块信息
     * 
     */
    private function getModuleInfo( $id )
    {
        if( empty($id) ){
            return zy_json_echo( false, '未找到相应模块！');
        }
        return Db::name( 'module_template' )->where( 'id' , $id )->find();
    }


    /**
     * 上传模板压缩文件
     */
    public function upResource($id)
    {
	
        $module = $this->getModuleInfo( $id );
        $path = cmf_parse_name( $module[ 'name' ] ).DS.$module['version'].DS.'template'.DS.$module['type'];
        return $this->uploadFile ( $path , 100 , ['zip'] );
    }

    /**
     *检查模板名称是否重复 
     */
    public function checkTemplateName()
    {
        if( !$this->request->isPost() ){
            return zy_json_echo(false , '请求类型错误!' );
        }
        $param = $this->request->param();
        $name = trim( $param['name'] );
        if( empty($name) ){
            return zy_json_echo(false, '模板名称不能为空!');
        }
        $find = Db::name( 'module_template' )->where( 'template_name' , $name )->find();
        if( empty( $find ) ){
            return zy_json_echo( true, '模板名称可用!' );
        }
        return zy_json_echo( false , '模板名称已存在,请重新输入!' );
    }
    

    //////////////////////////////////////////
    /**
     * 获取所有模块列表
     */
    private function getModuleList()
    {
        //获取通过一审 status  = 3 的所有模块信息
        $moduleInfo = Db::name( 'module_store' )->where( 'step' ,  '=' , 2 )->order('name')->field( 'name,title,version' )->select()->toArray();
        $list = [];
        foreach ( $moduleInfo as $key => $value ) {
            $version = $value [ 'version' ] ;
            $value [ 'version' ] = [] ;
            $list [ $value [ 'name' ] ] = $value;
            $list [ $value [ 'name' ] ] ['version'] [] = $version;
        }
        return $list;
    }


    ////////////////////////////////////////////////


    /**
     * 删除预览图
     */
    public function trashFile()
    {
        $data = $this->request->param();
        $file = $data['file'];
        $id = $data['id'];
        $preview = $data['preview'];
        if( !empty( $id ) ){
            //更新数据库数据
            Db::name( 'module_template' )->where( 'id' , $id )->update( [ 'preview' => $preview ]);
        }
        $path = APP_PATH.'..'.DS.'public'.DS.$file;
        if( file_exists( $path ) ){
            unlink( $path );
        }          
    }

    /**
     * 上传文件公共方法
     */
    private function uploadFile ( $path = '' , $size = 10 , $exts = ['zip'] , $fileName = '' )
    {
        try {
            $upload = new Upload();
            $upload->setSize( $size );
            if( !empty( $exts ) ){
                $upload->exts = $exts;
            }
            if( !empty( $fileName ) ){
                $upload->fileName = $fileName;
            }
            $upload->rootPath = $this->rootPath.DS.$path;
            $upload->setResourceInfo( $_FILES );
            return $upload->uploadFile(true);
        } catch (\Exception $e) {
            return zy_json_echo( false , $e->getMessage() );
        }
    }
	
	
	//模板分类
	public function classify()
	{
		$list = Db::name('module_template_classify')->select()->toArray();
		$this->assign( 'list' , $list );
		return $this->fetch( 'template/classify' );
	}

    /**
     * 添加分类
     */
    public function addClassify()
    {
        if( $this->request->isPost() ){
            //添加提交
            $param = $this->request->param();
            $name = $param [ 'name' ] ;
			$title = $param [ 'title' ];
			$find = Db::name('module_template_classify')->where('name' , $name )->find();
			if( !empty($find) ){
				return zy_json_echo( false , $name.' 标识已经存在，请检查！');
			}
            $res = Db::name('module_template_classify')->insertGetId( [ 'name' => $name , 'title' => $title ] );
            if( !$res ){
                return zy_json_echo( false , '添加分类失败,请稍后再试!' );
            }
            return zy_json_echo( true , '添加成功!' );
        }else{
            return $this->fetch('template/classify_add');
        }
    }

    /**
     * 编辑分类
     */
    public function editClassify()
    {
        $param = $this->request->param();
        $id = $param [ 'id' ] ;
        if( $this->request->isPost() ){
            //编辑数据提交
            $name = $param['name'];
			$title = $param['title'];
			$find = Db::name('module_template_classify')->where('name' , $name )->find();
			
			if( !empty($find) && $id != $find['id'] ){
				return zy_json_echo( false , $name.' 标识已经存在，请检查！');
			}
            $res = Db::name( 'module_template_classify' )->where( 'id' , $id )->update( [ 'name' => $name , 'title' => $title  ] );
            if( !$res ){
                return zy_json_echo( false, '修改数据失败,请稍后再试!' );
            }
            return zy_json_echo( true , '修改成功!' );
        }else{
            $find = Db::name( 'module_template_classify' )->where( 'id' , $id )->find();
			$this->assign('classify' , $find );
			return $this->fetch('template/classify_add');
        }
    }
	
	//delete classify
	public function delClassify($id)
	{
		$res = Db::name( 'module_template_classify' )->where( 'id' , $id )->delete();
		if( !$res ){
			return zy_json_echo( false , '删除失败，请稍候再试！' );
		}
		return zy_json_echo(true , '删除成功！');
	}
	
	//模板回退
	public function returnStep()
	{
		$param = $this->request->param();
		$id = $param['id'];
		$status = $param['status'];
		$res = Db::name( 'module_template' )->where('id' , $id )->update( ['status'=>$status] );
		if(!$res){
			return zy_json_echo( false , '回退操作失败，请稍候再试！' );
		}
		return zy_json_echo( true , '回退操作成功！' );
	}
	
	

}